import 'dart:async';

import 'package:lepig/common/EventBus.dart';
import 'package:lepig/common/SearchEvent.dart';
import 'package:lepig/common/SearchHistory.dart';
import 'package:lepig/common/enum/ShopType.dart';
import 'package:lepig/model/ProductModel.dart';
import 'package:lepig/model/SearchModel.dart';
import 'package:lepig/request/HttpSelectSearchProduct.dart';
import 'package:lepig/widget/GoodsHorizontalTwo.dart';
import 'package:lepig/widget/screenTab/ScreenTab.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Search extends StatefulWidget {
  Search({Key key, this.searchModel}) : super(key: key);
  SearchModel searchModel = new SearchModel();

  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  final timeout = const Duration(seconds: 2);
  Timer timer;
  final textController = TextEditingController();
  //搜索历史
  List<String> searchLists=[];

  String keyword = "";
  bool isKeyword = false;

  SearchModel searchModel = new SearchModel();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _searchController();
    getSearchHistory();
    searchModel = widget.searchModel;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return searchModel.isCate ? _category() : _search();
  }

  //获取搜索历史
  getSearchHistory(){
    SearchHistory.getKeyWords().then((value){
      searchLists=value;
    });
  }

  //分类搜索
  Widget _category() {
    return new Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Color.fromRGBO(247, 247, 247, 1),
        title: new Text(searchModel.keyword),
      ),
      body: _SearchResult(searchModel:searchModel),
    );
  }

  //普通搜索
  Widget _search() {
    return new Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Color.fromRGBO(247, 247, 247, 1),
        leading: new FlatButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: new Icon(Icons.arrow_back),
        ),
        title: new Align(
          child: Container(
            height: 35.0,
            alignment: Alignment.center,
            child: new Align(
              child: TextField(
                controller: textController,
                autofocus: false,
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.all(-2),
                    border: InputBorder.none,
                    hintText: "搜索好货",
                    prefixIcon: Icon(
                      Icons.search,
                      color: Color.fromRGBO(204, 204, 204, 1),
                    ),
                    suffixIcon: new IconButton(
                        icon: Icon(
                          Icons.clear,
                          color: Color.fromRGBO(204, 204, 204, 1),
                        ),
                        onPressed: () {
                          setState(() {
                            isKeyword = false;
                          });
                          //清除输入框
                          textController.text = "";
                        })),
              ),
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        actions: <Widget>[
          new Container(
            child: new FlatButton(
              onPressed: () {
                setState(() {
                  isKeyword = true;
                });
                if (this.keyword != null && this.keyword != "") {
                  SearchEntity sen = new SearchEntity();
                  sen.keyword = keyword;
                  eventBus.fire(new SearchEventEvent(sen));
                }
              },
              child: new Text("搜索"),
            ),
            alignment: Alignment.center,
            padding: EdgeInsets.only(right: 20.0),
            width: 80.0,
          )
        ],
      ),
      body: Stack(
        children: <Widget>[
          new Offstage(
            offstage: isKeyword,
            child: SearchTag(
              searchLists:searchLists,
              onTab: _searchLabel,
            ),
          ),
          new Offstage(
            offstage: !isKeyword,
            child: _SearchResult(),
          )
        ],
      ),
    );
  }

  //搜索标签
  _searchLabel(String label) {
    textController.text = label;
  }

  //搜索控制
  _searchController() {
    textController.addListener(() {
      this.keyword = textController.text;
    });
  }
}

//搜索标签
class SearchTag extends StatelessWidget {
  SearchTag({this.searchLists,this.onTab});

  List<String> searchLists;
  Function onTab;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Column(
      children: <Widget>[
//        new _Tag(
//          "热门搜索",
//          ["苹果手机壳", "三只松鼠", "牛肉干"],
//          1,
//          onTab: (title) {
//            this.onTab(title);
//          },
//        ),
        new _Tag(
          "搜索历史",
          searchLists,
          2,
          onTab: (title) {
            this.onTab(title);
          },
          onClear: () {},
        ),
      ],
    );
  }
}

class _Tag extends StatelessWidget {
  _Tag(this.label, this.tgas, this.type, {this.onTab, this.onClear});

  String label;
  List<String> tgas;
  int type;
  Function onTab;
  Function onClear;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Padding(
      padding: EdgeInsets.only(left: 10.0, right: 10.0, top: 20.0),
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              new Text(
                this.label,
                style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),
              ),
              type == 1
                  ? new SizedBox()
                  : new FlatButton.icon(
                      onPressed: () {
                        this.onClear();
                      },
                      label: new Text(
                        "清空记录",
                        style: TextStyle(
                            fontSize: 13.0,
                            color: Color.fromRGBO(164, 164, 164, 1)),
                      ),
                      icon: Icon(
                        Icons.delete,
                        size: 13.0,
                        color: Color.fromRGBO(164, 164, 164, 1),
                      ),
                    )
            ],
          ),
          Wrap(
            spacing: 8.0, // 主轴(水平)方向间距
            runSpacing: 4.0, // 纵轴（垂直）方向间距
            alignment: WrapAlignment.start,
            children: this.tgas.map((title) {
              return _hotTag(title, this.type, onTab);
            }).toList(),
          )
        ],
      ),
    );
  }

  Widget _hotTag(String title, int type, Function onTab) {
    return new Chip(
      label: InkWell(
        child: new Text(title),
        onTap: () {
          this.onTab(title);
        },
      ),
      backgroundColor: type == 1
          ? Color.fromRGBO(253, 250, 233, 1)
          : Color.fromRGBO(241, 241, 241, 1),
      padding: EdgeInsets.only(left: 8.0, right: 8.0),
    );
  }
}

//搜索结果
class _SearchResult extends StatefulWidget {
  _SearchResult({Key key,this.searchModel}):super(key:key);
  SearchModel searchModel;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _SearchResultState();
  }
}

class _SearchResultState extends State<_SearchResult>
    with SingleTickerProviderStateMixin {
  StreamSubscription<dynamic> _colorSubscription;

  List<ProductModel> products = [];

  //tab索引
  int tabIndex = 1;

  //搜索关键字
  String keyword = "";

  //分类

  int page = 1;

  //分类id
  String type = getShopType("tb"); //商城分类
  bool isCoupon;
  String sort = "";

  //是否加载中
  bool _onLoading = true;

  // 是否加载完毕
  bool _done = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.searchModel!=null){
      this.keyword=widget.searchModel.keyword;
      _tabChangeSearch();
    }
    eventBus.on<SearchEventEvent>().listen((event) {
      if (this.keyword != event.searchEntity.keyword) {
        this.keyword = event.searchEntity.keyword;
        _tabChangeSearch();
      }
    });
  }

  getSearch() {
    if (mounted) {
      setState(() {
        _onLoading = false;
      });
    }

    HttpSelectSearchProduct(this.context,
            q: keyword, type: type, page: page, isCoupon: isCoupon, sort: sort)
        .then((value) {
      if (mounted) {
        if (value == null || value.length == 0) {
          setState(() {
            this._done = true;
            _onLoading = true;
          });
          return;
        }
        SearchHistory.saveKeyWord(keyword);
        setState(() {
          _onLoading = true;
          products.addAll(value);
        });
        page += 1;
      }
    });
  }

  //tab 商城选择 切换
  _tabChangeSearch() {
    products = [];
    page = 1;
    isCoupon = null;
    sort = null;
    _done = false;
    getSearch();
  }

  //筛选切换
  _screenTab() {
    this.page = 1;
    this.products = [];
    getSearch();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (_colorSubscription != null) {
      _colorSubscription.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
      color: Color.fromRGBO(242, 242, 242, 1),
      child: new Column(
        children: <Widget>[
          new Container(
            color: Color.fromRGBO(247, 247, 247, 1),
            height: 50.0,
            child: _tabSelect(),
          ),
          new Container(
            color: Colors.white,
            height: 50.0,
            child: ScreenTab(onFunction: (s, v) {
              this.isCoupon = v;
              this.sort = s;
              _screenTab();
            }),
          ),
          new Container(
            height: 10.0,
          ),
          new NotificationListener(
            // ignore: missing_return
            onNotification: (ScrollNotification notification) {
              //到底部小于20 就刷新
              if (!_done &&
                  notification.metrics.extentAfter < 20 &&
                  _onLoading) {
                getSearch();
              }
            },
            child: new Expanded(
              child: (_done&&page==1)?new Align(child: new Text("没有搜索到结果!"),):new Container(
                color: Color.fromRGBO(242, 242, 242, 1),
                padding: EdgeInsets.only(left: 10, right: 10),
                child: GridView.builder(
                  shrinkWrap: true,
                  itemCount: products.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GoodsHorizontalTwo(products[index]);
                  },
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      childAspectRatio: 0.560,
                      crossAxisCount: 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10),
                ),
              ),
            ),
          ),
          !_onLoading
              ? new Container(
                  child: new Align(
                    child: new Text(this._done?"没有数据了":"加载中..."),
                  ),
                  height: 20.0,
                )
              : new SizedBox(),

        ],
      ),
    );
  }

  //选择
  Widget _tabSelect() {
    return new Flex(
      direction: Axis.horizontal,
      children: <Widget>[
        _tabItem(1, "淘宝"),
        _tabItem(3, "京东"),
        _tabItem(4, "拼多多"),
      ],
    );
  }

  Widget _tabItem(int index, String title) {
    TextStyle notSelect =
        TextStyle(fontSize: 19.0, fontWeight: FontWeight.w500);
    TextStyle onSelect = TextStyle(
        fontSize: 19.0, fontWeight: FontWeight.bold, color: Colors.red);
    BoxDecoration notBox = BoxDecoration();
    BoxDecoration onBox = BoxDecoration(
      border: Border(bottom: BorderSide(color: Colors.red, width: 3)),
    );
    TextStyle select = this.tabIndex == index ? onSelect : notSelect;
    BoxDecoration box = this.tabIndex == index ? onBox : notBox;
    return new Expanded(
      child: new Container(
        child: new InkWell(
          child: new Container(
            padding: EdgeInsets.only(bottom: 5.0),
            decoration: box,
            child: new Text(
              title,
              style: select,
            ),
          ),
          onTap: () {
            setState(() {
              this.tabIndex = index;
              this.type = index.toString();
            });
            _tabChangeSearch();
          },
        ),
        alignment: Alignment.center,
      ),
      flex: 1,
    );
  }
}
